def solve():
    # 使用测试数据
    n = 5
    exit_sequence = [1, 3, 5, 2, 4]
    
    print(f"输入: n={n}, 出站序列={exit_sequence}")
    
    # 记录每辆火车的出站顺序
    exit_order = {}
    for i, train in enumerate(exit_sequence):
        exit_order[train] = i
    
    print(f"出站顺序: {exit_order}")
    
    # 模拟过程
    station = []  # 栈，表示当前在站内的火车
    exit1_count = 0
    current_train = 1  # 下一辆要进站的火车
    
    for target_train in exit_sequence:
        print(f"\n处理火车{target_train}:")
        
        # 让所有需要的火车进站
        while current_train <= target_train:
            station.append(current_train)
            print(f"  火车{current_train}进站，当前站内: {station}")
            current_train += 1
        
        # 检查目标火车是否在栈顶或栈底
        if not station:
            print(-1)
            return
        
        can_exit = False
        exit_from_1 = False
        
        # 尝试从出站口1出站（栈顶）
        if station[-1] == target_train:
            print(f"  火车{target_train}在栈顶，尝试从出站口1出站")
            # 检查出站口1方向是否有其他火车阻挡
            can_exit_from_1 = True
            for remaining_train in station[:-1]:  # 除了栈顶的火车
                if exit_order[remaining_train] > exit_order[target_train]:
                    can_exit_from_1 = False
                    print(f"  火车{target_train}被火车{remaining_train}阻挡（{remaining_train}比{target_train}晚出站）")
                    break
            
            if can_exit_from_1:
                station.pop()
                can_exit = True
                exit_from_1 = True
                print(f"  火车{target_train}从出站口1出站，剩余站内: {station}")
            else:
                print(f"  火车{target_train}无法从出站口1出站")
        
        # 如果无法从出站口1出站，尝试从出站口2出站（栈底）
        if not can_exit and station[0] == target_train:
            print(f"  火车{target_train}在栈底，尝试从出站口2出站")
            # 检查出站口2方向是否有其他火车阻挡
            can_exit_from_2 = True
            for remaining_train in station[1:]:  # 除了栈底的火车
                if exit_order[remaining_train] > exit_order[target_train]:
                    can_exit_from_2 = False
                    print(f"  火车{target_train}被火车{remaining_train}阻挡（{remaining_train}比{target_train}晚出站）")
                    break
            
            if can_exit_from_2:
                station.pop(0)  # 从栈底移除
                can_exit = True
                exit_from_1 = False
                print(f"  火车{target_train}从出站口2出站，剩余站内: {station}")
            else:
                print(f"  火车{target_train}无法从出站口2出站")
        
        if not can_exit:
            print(f"  火车{target_train}无法出站")
            print(-1)
            return
        
        if exit_from_1:
            exit1_count += 1
            print(f"  出站口1计数: {exit1_count}")
    
    print(f"\n最终结果: {exit1_count}")

if __name__ == "__main__":
    solve()
